var WorkshopIssue = function () {
  var SearchForm = function () {
    var template = /* html */ `
      <div class="search-form" v-loading.fullscreen.lock="loading">
        <sys-common-search request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:26}"
          :search="search" :search-field="searchField" label-width="auto" input-width="180px">
          <template slot="prepend">
            <el-form-item label="部门-车间">
              <el-cascader filterable clearable v-model="search.deptWork" style="width:180px" :options="deptWorkList"
                :props="props" separator="-"></el-cascader>
            </el-form-item>
          </template>
        </sys-common-search>
      </div>
    `;

    return {
      props: {
        search: {
          type: Object,
          required: true
        }
      },

      data: function () {
        return {
          loading: false,
          searchField: ['companyOrderId', 'orderId', 'factoryId', 'coustomId', 'materialName', 'model', 'color',
            'providerName', 'materialDept'
          ],
          deptWorkList: [],
          props: {
            value: 'id',
            label: 'name'
          }
        };
      },

      created: function () {
        this.setDeptList();
      },

      methods: {
        setDeptList: function () {
          this.loading = true;
          var self = this;
          ajaxRequest('equipment/getDepartmentDropdown').then(function (deptWorkList) {
            deptWorkList = _.map(deptWorkList, function (deptWork) {
              var obj = {
                id: deptWork.departmentCode,
                name: deptWork.deptName
              };

              var workshops = deptWork.workshops;
              workshops = _.map(workshops, function (workshop) {
                return {
                  id: workshop.id,
                  name: workshop.workshopName
                };
              });
              if (!SysUtil.isEmpty(workshops)) {
                obj.children = workshops;
              }
              return obj;
            });

            self.deptWorkList = deptWorkList;
            self.loading = false;
          }).catch(function () {
            self.loading = false;
          });
        }
      },

      components: {
        SysCommonSearch: SysCommonSearch
      },

      template: template
    };
  }();

  var template = /* html */ `
    <div class="workshop-issue" v-loading.fullscreen.lock="loading">
      <search-btn-view immediate btn-text="查询" @before-open="resetSearch" @search="searchData">
        <template slot="append">
          <el-button v-if="selectStatList.length>0" size="medium" type="primary" @click="issueMaterial">批量发料</el-button>
        </template>
        <div slot="search-content">
          <search-form :search="search"></search-form>
        </div>
      </search-btn-view>
      <div class="workshop-issue-table-div">
        <el-table fit stripe border :data="statList" style="width:100%;" height="parent" @selection-change="selectionChange">
          <el-table-column type="selection" width="40px" align="center" fixed="left" :selectable="canIssue"></el-table-column>
          <el-table-column sortable label="车间" prop="workShopName" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable label="订单编号" prop="companyOrderId" min-width="140px" header-align="center"></el-table-column>
          <el-table-column sortable label="工厂型号" prop="factoryNo" min-width="130px" header-align="center"></el-table-column>
          <el-table-column sortable label="客户型号" prop="articleNo" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="订单序号" prop="lineNo" width="100px" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.lineNo==='-1'?globalConfig.orderDefaultRowIndex:scope.row.lineNo}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="供应商" prop="providerName" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="物料名称" prop="materialName" min-width="140px" header-align="center"></el-table-column>
          <el-table-column sortable label="规格" prop="model" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="编号" prop="color" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="描述" prop="colorDescription" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="物料部门" prop="materialDeptName" min-width="120px" align="center"></el-table-column>
          <el-table-column sortable label="供方编号" prop="providerNo" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="订单投料数" prop="feedTotal" min-width="110px" align="center"></el-table-column>
          <el-table-column sortable label="投料数" prop="feedCount" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable label="库存数" prop="warehouseCount" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable label="单位" prop="unit" min-width="100px" align="center"></el-table-column>
          <el-table-column :resizable="false" label="发料数" width="140px" header-align="center">
            <template slot-scope="scope" v-if="scope.row.maxIssueCount!==null">
              <el-input-number v-model="scope.row.issueCount" :min="1/Math.pow(10,scope.row.precision)" :max="scope.row.maxIssueCount"
                :precision="scope.row.precision" size="mini" :controls="false" @change="issueCountChange(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="交接数" min-width="140px" align="center">
            <template slot-scope="scope" v-if="scope.row.maxIssueCount!==null">
              <span v-if="scope.row.singleFeedCount!==null">{{scope.row.selfOutFuCount}}</span>
              <el-input-number v-else v-model="scope.row.selfOutFuCount" :min="1" :precision="0" size="mini" :controls="false">
              </el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>
    </div>
  `;

  return {
    mixins: [
      tablePaginationMixin()
    ],

    data: function () {
      var search = {
        companyOrderId: '',
        orderId: '',
        factoryId: '',
        coustomId: '',
        materialName: '',
        model: '',
        color: '',
        providerName: '',
        materialDept: '',
        deptWork: []
      };
      return {
        loading: false,
        statList: [],
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        selectStatList: []
      };
    },

    methods: {
      setStatList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var search = this.search;
        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize
        }

        var deptWork = search.deptWork;
        var workShopId = deptWork[1];
        if (!SysUtil.isEmpty(workShopId)) {
          postData.workShopId = workShopId;
        }

        var fields = ['companyOrderId', 'orderId', 'factoryId', 'coustomId', 'materialName', 'model', 'color', 'providerName'];
        SysUtil.setPostData(postData, search, fields);

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }

        this.loading = true;
        var self = this;
        ajaxRequest("issueNote/getWorkShopWarehouseMaterialCount", postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          var statList = res.returnData;
          for (var i = 0; i < statList.length; i++) {
            var stat = statList[i];
            stat.model = stat.modal;
            SysUtil.tableSetDeptData(stat);

            var lineNo = stat.lineNo;
            if (!SysUtil.isEmpty(lineNo)) {
              stat.lineNo = Number(lineNo);
            }

            var precision = SysUtil.getMaterialNumberPrecision(stat.unit, 4);
            stat.precision = precision;

            var receiveCount = stat.receiveCount;
            var warehouseCount = stat.warehouseCount;
            if (receiveCount > 0 && warehouseCount > 0) {
              receiveCount = Math.min(receiveCount, warehouseCount);
              if (receiveCount <= 0) {
                receiveCount = null;
              }
            } else {
              receiveCount = null;
            }
            stat.issueCount = receiveCount;
            stat.maxIssueCount = receiveCount;

            var feedCount = stat.feedCount;
            var feedTotal = stat.feedTotal;
            var singleFeedCount;
            if (SysUtil.isEmpty(feedCount) || SysUtil.isEmpty(feedTotal) || stat.type === 2) {
              singleFeedCount = null;
            } else {
              singleFeedCount = feedCount / feedTotal;
            }
            stat.singleFeedCount = singleFeedCount;

            if (singleFeedCount !== null) {
              var count = receiveCount ? receiveCount : 0;
              var selfOutFuCount = count / singleFeedCount;
              selfOutFuCount = _.round(selfOutFuCount, 4);
              stat.selfOutFuCount = Math.floor(selfOutFuCount);
            } else {
              stat.selfOutFuCount = undefined;
            }
          }

          self.statList = statList;
          self.pagination.totalCount = res.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setStatList(true);
      },

      pageChange: function () {
        this.setStatList();
      },

      issueCountChange: function (stat) {
        var singleFeedCount = stat.singleFeedCount;
        if (singleFeedCount === null) {
          return;
        }
        var count = stat.issueCount ? stat.issueCount : 0;
        var selfOutFuCount = count / singleFeedCount;
        selfOutFuCount = _.round(selfOutFuCount, 4);
        stat.selfOutFuCount = Math.floor(selfOutFuCount);
      },

      canIssue: function (stat) {
        return stat.maxIssueCount !== null;
      },

      selectionChange: function (selectStatList) {
        this.selectStatList = selectStatList;
      },

      issueMaterial: function () {
        var selectStatList = this.selectStatList;
        if (selectStatList.length === 0) {
          this.$alert('请需要发料的订单物料', '信息');
          return;
        }

        var postDataList = [];
        var fiels = ['id', 'orderId', 'materialCode'];
        for (var i = 0; i < selectStatList.length; i++) {
          var stat = selectStatList[i];
          if (!this.checkValid(stat)) {
            return;
          }

          var color = stat.color.trim();
          if (color === '' || color === '无') {
            color = stat.model;
          }

          var postData = {
            color: color,
            workShopName: stat.useFactoryId,
            rowIndex: String(stat.lineNo),
            machining: stat.materialType,
            qualified: stat.selfOutFuCount,
            materialCount: stat.issueCount,
            materialUnit: stat.unit
          }
          SysUtil.setPostData(postData, stat, fiels, false, true);
          postDataList.push(postData);
        }

        this.loading = true;
        var self = this;
        ajaxRequest('issueNote/manualIssue', {
          jsonArray: JSON.stringify(postDataList)
        }).then(function (msg) {
          self.$alert('批量发料成功', '信息', {
            callback: function () {
              self.setStatList();
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      checkValid: function (stat) {
        if (SysUtil.isEmpty(stat.issueCount)) {
          this.$alert('请输入发料数', '信息');
          return false;
        }

        var singleFeedCount = stat.singleFeedCount;
        var selfOutFuCount = stat.selfOutFuCount;
        if (singleFeedCount === null) {
          if (SysUtil.isEmpty(selfOutFuCount)) {
            this.$alert('请输入交接数', '信息');
            return false;
          }
        } else {
          if (selfOutFuCount === 0) {
            this.$alert('交接数不能为0', '信息');
            return false;
          }
        }
        return true;
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      SearchForm: SearchForm
    },

    template: template
  };
}();
